import { defineStore } from 'pinia'
import { ref } from 'vue'
import { loginApi, getUserListApi } from '@/api/login'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'

export const useUserStore = defineStore(
  'userstore',
  () => {
    // 注意router初始化必须写在pinia的回调函数里面，卸载全局会报错
    const router = useRouter()
    const token = ref('')
    const user = ref([])
    const currentUser = ref([{ username: '', useravatar: '' }])
    const setToken = (newtoken) => {
      token.value = newtoken
    }
    const removeToken = () => {
      token.value = ''
    }
    const loginAction = async (userinfo) => {
      const result = await loginApi(userinfo)
      console.log(result)
      //   1表示失败，0表示登陆成功
      if (result.status) {
        ElMessage.error(result.message)
      } else {
        ElMessage.success(result.message)
        currentUser.value = {
          username: userinfo.username,
          useravatar: userinfo.useravatar
        }
        setTimeout(() => {
          router.push('/chat')
        }, 1000)
      }
      token.value = result.token
    }

    const getUserListAction = async () => {
      const result = await getUserListApi()
      console.log(result)
      user.value = result.data.user
    }

    return {
      token,
      user,
      currentUser,
      setToken,
      removeToken,
      loginAction,
      getUserListAction
    }
  },
  {
    persist: true
  }
)
